<?php
class Mageex_AdvanceSeo_Model_Layer_Filter_Item extends Mage_Catalog_Model_Layer
{
    /**
     * Get filter instance
     *
     * @return Mage_Catalog_Model_Layer_Filter_Abstract
     */
    public function getFilter()
    {
        $filter = $this->getData('filter');
        if (!is_object($filter)) {
            Mage::throwException(
                Mage::helper('catalog')->__('Filter must be an object. Please set correct filter.')
            );
        }
        return $filter;
    }
	/**
     * Get url info
     *
     * @return array
     */
	protected function getUrlInfo($subfix)
	{
		$arrUrlInfo		= array();
		//$arrParams		= Mage::app()->getRequest()->getParams();
		$pathInfo 		= $_SERVER['REQUEST_URI'];
		$pathInfo		= trim(trim($pathInfo, '/'), $subfix);
		$arrUrlInfo		= explode('/', $pathInfo);
		
		array_shift($arrUrlInfo);
		array_shift($arrUrlInfo);	
		return $arrUrlInfo;
	}
	/**
     * Get filterable attributes name
     *
     * @return array
     */
	protected function getFilterableAttributesName($removeValue=null)
	{
		$arrAttribute	= array();
		$attribute 		= $this->getFilterableAttributes();
		
		foreach($attribute as $attr){
			if($removeValue==null){
				$arrAttribute[] = $attr->getName();
			}else{
				if($removeValue!=$attr->getName()){
					$arrAttribute[] = $attr->getName();
				}
			}
			
		}
		
		return $arrAttribute;
	}
	/**
     * Get url sorted
     *
     * @return string
     */
	 protected function getUrlSorted($arrAttribute,$arrUrlInfo,$urlRewrite,$removeCategory=false)
	 {
			
		 	$newArr 		= array();
			$strCat 		= '';
			$requestVar 	= $this->getFilter()->getRequestVar();
			$requestValue	= Mage::helper('advanceseo/data')->stringConvert($this->getLabel());
			
			foreach($arrAttribute  as $key=>$value){
				foreach($arrUrlInfo as $keyInfo=>$valueInfo){
				
					$info = explode('-',$valueInfo);
					if($removeCategory==false){
						if($info[0]=='cat'){
							$strCat = $valueInfo;
						}
						if($valueInfo=='cat'){
							$strCat= $requestVar . '-' .$requestValue;
						}
					}	
					if($value==$info[0]){
						$newArr[] = $valueInfo;
					}
				}
			}
			
			if($strCat != ''){
				$urlRewrite  .= $strCat .'/';
			}
			
			foreach($newArr as $value){
				if($value==$requestVar){
					if($requestVar=='price'){
						$urlRewrite.=$requestVar . '-' .$this->getValue() . '/';
					}else{
						$urlRewrite.=$requestVar . '-' .$requestValue . '/';
					}
				}else{
					$urlRewrite.=$value . '/';
				}
			}
			return $urlRewrite;
	 }
	 
    /**
     * Get filter item url
     *
     * @return string
     */
    public function getUrl()
    {
    	if(Mage::helper('advanceseo/config')->isEnableRewriteFilter()){
			$requestVar 	= $this->getFilter()->getRequestVar();
			$arrAttribute 	= $this->getFilterableAttributesName();
			
			//echo $requestVar 	= $this->getFilter()->getRequestVar().$this->getLabel();
	
			$baseUrl		= Mage::helper('advanceseo/data')->getCurrentUrl();
			
			$urlRewrite 	= $baseUrl. '/';
				
			
			$requestValue	= Mage::helper('advanceseo/data')->stringConvert($this->getLabel());
			$subfix			= Mage::helper('advanceseo/data')->getSuffix();
			
			$arrUrlInfo		= $this->getUrlInfo($subfix);
			
			$arrUrlInfo[] 	= $requestVar;
			
			$urlRewrite	= $this->getUrlSorted($arrAttribute, $arrUrlInfo, $urlRewrite);
				
			$urlRewrite = trim($urlRewrite,'/');
			$urlRewrite .= $subfix;
			
   			return $urlRewrite;
			
    	}else{
	        $query = array(
            $this->getFilter()->getRequestVar()=>$this->getValue(),
            Mage::getBlockSingleton('page/html_pager')->getPageVarName() => null // exclude current page from urls
       		 );
      		return Mage::getUrl('*/*/*', array('_current'=>true, '_use_rewrite'=>true, '_query'=>$query));
    	} 	
    }
    /**
     * Get url for remove item from filter
     *
     * @return string
     */
    public function getRemoveUrl()
    {
		if(Mage::helper('advanceseo/config')->isEnableRewriteFilter()){
			$requestVar 	= $this->getFilter()->getRequestVar();
			$arrAttribute 	= $this->getFilterableAttributesName($requestVar);
			
			$urlRewrite 	= Mage::helper('advanceseo/data')->getCurrentUrl(). '/';
			
			$requestValue	= Mage::helper('advanceseo/data')->stringConvert($this->getLabel());
			$subfix			= Mage::helper('advanceseo/data')->getSuffix();
			
			$arrUrlInfo		= $this->getUrlInfo($subfix);
			
			if($requestVar=='cat'){
				$urlRewrite	= $this->getUrlSorted($arrAttribute, $arrUrlInfo, $urlRewrite,true);
				//echo $urlRewrite;
			}else{	
				$arrUrlInfo[] 	= $requestVar;	
				$urlRewrite	= $this->getUrlSorted($arrAttribute, $arrUrlInfo, $urlRewrite);
			}
			
			$key = array_keys($arrUrlInfo, Mage::helper('advanceseo/config')->getPathFilter());
			$count=0;
			
			for($i=0; $i<count($arrUrlInfo); $i++){
				if($i>$key[0] && ($arrUrlInfo[$i] != $requestVar)){
					$count++;
				}
			}
			if($count==1){
				$urlRewrite = trim(trim($urlRewrite,'/'), Mage::helper('advanceseo/config')->getPathFilter());
			}
			$urlRewrite = trim($urlRewrite,'/');
			$urlRewrite .= $subfix;;
	
			return $urlRewrite;
		}else{
			$query = array($this->getFilter()->getRequestVar()=>$this->getFilter()->getResetValue());
			$params['_current']     = true;
			$params['_use_rewrite'] = true;
			$params['_query']       = $query;
			$params['_escape']      = true;
			return Mage::getUrl('*/*/*', $params);
		}
		
    }

    /**
     * Get item filter name
     *
     * @return string
     */
    public function getName()
    {
        return $this->getFilter()->getName();
    }

    /**
     * Get item value as string
     *
     * @return string
     */
    public function getValueString()
    {
        $value = $this->getValue();
        if (is_array($value)) {
            return implode(',', $value);
        }
        return $value;
    }
}
